package java_thinking.unit_17._17_2_6;

import java.util.*;

/**
 * @Desc:   7 未支持的操作示例
 *          因为Arrays.asList()会生成一个List，它基于一个固定大小的数组，仅支持纳西额不会改变数组大小的操作，
 *          对它而言是有道理的，任何会引起对底层数据结构的尺寸进行修改的方法都会产生一个UnsupportedOperationException
 *          异常，以表示对未获支持的调用(一个编程错误)
 * @author: cww
 * @DateTime: 2019/4/15 20:00
 */

public class Unsupported {
    static void test(String msg, List<String> list) {
        System.out.println("--- " + msg + " ---");
        Collection<String> c = list;
        Collection<String> subList = list.subList(1,8);
        // Copy of subList:
        Collection<String> c2 = new ArrayList<String>(subList);
        try { c.retainAll(c2); } catch(Exception e) {
            System.out.println("retainAll(): " + e);
        }
        try { c.removeAll(c2); } catch(Exception e) {
            System.out.println("removeAll(): " + e);
        }
        try { c.clear(); } catch(Exception e) {
            System.out.println("clear(): " + e);
        }
        try { c.add("X"); } catch(Exception e) {
            System.out.println("add(): " + e);
        }
        try { c.addAll(c2); } catch(Exception e) {
            System.out.println("addAll(): " + e);
        }
        try { c.remove("C"); } catch(Exception e) {
            System.out.println("remove(): " + e);
        }
        // The List.set() method modifies the value but
        // doesn't change the size of the data structure:
        try {
            list.set(0, "X");
        } catch(Exception e) {
            System.out.println("List.set(): " + e);
        }
        // Additional optional List methods:
        try { list.add(0, "X"); } catch(Exception e) {
            System.out.println("List.add(): " + e);
        }
        try { list.addAll(0, c2); } catch(Exception e) {
            System.out.println("List.addAll(): " + e);
        }
        try { list.remove(0); } catch(Exception e) {
            System.out.println("List.remove(): " + e);
        }
        try { list.removeAll(c2); } catch(Exception e) {
            System.out.println("List.removeAll(): " + e);
        }
        try { list.retainAll(c2); } catch(Exception e) {
            System.out.println("List.retainAll(): " + e);
        }
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("A B C D E F G H I J K L".split(" "));
        test("Modifiabe Copy", new ArrayList<String>(list));
        test("Arrays.asList()", list);
        test("unmodifiableLlist()",
        Collections.unmodifiableList(new ArrayList<String>(list)));
    }
}
